package com.wjk.kylin.mall.product.utils;

import org.elasticsearch.search.Scroll;

import java.util.Iterator;
import java.util.List;

/**
 * 迭代器 查询es
 *
 * @param <T>
 */
public class EsIterator<T> implements Iterator<T> {
    private Scroll scroll;
    private String scrollId;
    private long totalSize;
    private long totalIndex;
    private int from;
    private List<T> rows;
    private Class<T> clazz;
    private EsClientUtil clientUtil;

    /**
     * @param scroll
     * @param scrollId
     * @param clientUtil
     * @param totalSize
     * @param rows
     * @param clazz
     */
    public EsIterator(Scroll scroll, String scrollId, EsClientUtil clientUtil, long totalSize, List<T> rows, Class<T> clazz) {
        this.scroll = scroll;
        this.scrollId = scrollId;
        this.totalSize = totalSize;
        this.rows = rows;
        this.totalIndex = 0L;
        this.from = 0;
        this.clazz = clazz;
        this.clientUtil = clientUtil;
    }

    /**
     * 是否还有下一个
     *
     * @return
     */
    @Override
    public boolean hasNext() {
        if (this.rows.size() > 0 && this.from < this.rows.size()) {
            return true;
        } else if (this.rows.size() > 0 && this.from == this.rows.size()) {
            this.rows = this.clientUtil.selectScroll(this.scroll, this.scrollId, this.clazz);
            if (this.rows.size() > 0) {
                this.from = 0;
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 获取下一个
     *
     * @return
     */
    @Override
    public T next() {
        this.totalIndex++;
        T t = this.rows.get(this.from);
        this.from++;
        return t;
    }
}
